package com.speedchina.oauth2_permission.config.enhancer;

import com.baomidou.mybatisplus.core.toolkit.BeanUtils;
import com.speedchina.framework.utils.ApplicationContextHolder;
import com.speedchina.permission.domain.sys.entity.User;
import com.speedchina.permission.service.sys.UserService;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.Map;

/**
 * @author Winter
 * @date 2021年07月10日 23:46
 */
public class CustomTokenEnhancer extends JwtAccessTokenConverter {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        org.springframework.security.core.userdetails.User user = (org.springframework.security.core.userdetails.User) authentication.getPrincipal();
        UserService userService = ApplicationContextHolder.getBean(UserService.class);
        User u = userService.getByUserName(user.getUsername());
        // 注意添加的额外信息，最好不要和已有的json对象中的key重名，容易出现错误
        Map<String, Object> additionalInfo = BeanUtils.beanToMap(u);
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo);

        return accessToken;
    }
}
